package xim

import (
	"gitee.com/xiaoyutab/xgotool/optional/xcache"
	"gitee.com/xiaoyutab/xgotool/optional/xlog"
	"gitee.com/xiaoyutab/xgotool/xerror"
	"gitee.com/xiaoyutab/xgotool/xnum"
)

// 检测用户是否在群中
func CheckUserChat(uid uint, cid uint64) error {
	cache_key := xcache.Key("xim.check.user.chat", cid)
	uids := []uint{}
	err := xerror.New("数据库查询")
	if xcache.Exists(cache_key) {
		err = xcache.GetStruct(cache_key, &uids)
	}
	if err != nil {
		// 缓存中不存在，需要从数据库中进行查找
		if _default.DB == nil {
			return xerror.New("数据库未连接")
		}
		err = _default.DB.Table(_default.ChatUserTable).Where("is_deleted", 0).Where("chat_id", cid).Select("user_id").Group("user_id").Find(&uids).Error
		if err != nil {
			return xlog.AE("获取群成员列表失败", err)
		}
		xcache.SetStruct(cache_key, uids)
	}
	if !xnum.InArray(uid, uids) {
		return xerror.New("您还不是该聊天组成员")
	}
	return nil
}
